import { Avatar, Button, Card, message, Modal } from 'antd'
import TextEditor from '../../Components/TextEditor'
import React, { useCallback, useEffect, useRef, useState } from 'react'
import './index.scss'
import { useHistory } from 'react-router-dom'
import useStores from 'Stores'
import { dateRender } from 'Utils'
import { CommentMenuConfig } from 'Components/TextEditor/editorMenuConfig'
import axios from 'axios'
import { Spin } from 'antd';
import { CommentIcon,} from 'Global/Icon'
import CommentDeatil from 'Pages/CommentDetail'
import E from 'wangeditor'
type PostParam = {
  id:number
  content:string
  write_time:string
  commentCount:number
}

export interface Abstractimage<T>{
  author:T
  labels:T[]
  comments:T[]
}

export type labels ={
  id:number
  name:string
}

export type UserAuthors ={
  id:number
  name:string
  avatarUrl:string
}
export type OtherAuthors ={
  id:number
  content:string
  commentId:string
  createTime:UserAuthors
}

type ListdetailedData = (Abstractimage<UserAuthors> | Abstractimage<labels> | Abstractimage<OtherAuthors>)&{
  id: number
  content: string
  createTime:string
  updateTime: string
  images:string[]
}

const PostPage = () => {
  const [mainContent, setMainContent] = useState<string>('')
  const [showBtn, setShowBtn] = useState<boolean>(true)
  const { root,post} = useStores()
  const history = useHistory<PostParam>()
  const [listdetailedData, setListdetailedData] = useState<ListdetailedData[]>([])
  const [loading, setLoading] = useState<boolean>(true)
  const [commentModal,setcommentModal] = useState(false)//评论详情
  const [zcommentId,setZcommentId] = useState<number>()//评论的Id
  const [showname,setshowName] = useState('')
  const ref = useRef<E>(new E('.editor'))
  
  if(!history.location.state){
    history.replace('/')
  }
  const { id,content,write_time, } = history.location.state 

  
  const fetchdetailed = useCallback(async () => {
    axios.get(`http://localhost:3000/moment/${id}`)
    .then(function (response) {
      const list = response.data as ListdetailedData[]
      setListdetailedData(
     list
    )
    setLoading(false)
    })
    .catch(function (error) {
      console.log(error);
    });
  }, [id])

  useEffect(() => {
    fetchdetailed()
  }, [fetchdetailed])

  const onComment=async()=>{
    if(!mainContent.length){
      message.error(`评论不能为空`)
    }
    const res = await root.onComment(
      id,
      mainContent
    )
    if (res.affectedRows === 1) {
      setShowBtn(false)
      setMainContent('')
      ref.current.txt.clear()
      message.success('发表评论成功')
      fetchdetailed()
      return
    }
    message.error(`发表评论失败！${res}`)
  }

  const deleteComment = async(commentid:number)=>{
    if(!root.isLogin){
      message.error('请先登陆')
      return 
    }
    const res = await post.deleteComment(commentid)
    if (res.affectedRows === 1) {
      message.success('删除成功')
      setMainContent('')
      fetchdetailed()
      return
    }
    message.error(`删除失败！${res}`)
  }



  return (
    <>
    <div className="post-body">
      {!loading ? (
        <div>
      <Card style={{ paddingBottom: 100 }}>
        <div>
          <p className="post-page-title"> <div dangerouslySetInnerHTML={{ __html: content || '' }} /></p>
        </div>
        <div className="writer-msg">
          <Avatar
            size="large"
            src={(listdetailedData[0].author as UserAuthors).avatarUrl}
          />
          <div style={{ marginLeft: 10 }}>
            <div>{(listdetailedData[0].author as UserAuthors).name}</div>
            <div className="writer-detail">{dateRender(write_time, true)}</div>
          </div>
        </div>
        
        <div className="post-page-summary">话题标签：{(listdetailedData[0]?.labels as labels[])?.map((item,index) => {
          return <div className='label'>{item.name}</div>
        })}</div>
        <div dangerouslySetInnerHTML={{ __html: listdetailedData[0].content || '' }} />
      </Card>
      
      <Card style={{ marginTop: 15 }}>
      {root.isLogin ? (
        <>

        <div className="comment-editor">
          <TextEditor
          editor={ref.current}
            setState={setMainContent}
            menusItem={CommentMenuConfig}
            placeholder="写下你的评论......"
            onFocus={() => setShowBtn(true) }
          />
        </div>
        <div className={`comment-btn-group ${showBtn ? 'showBtn' : 'hideBtn'}`}>
          <Button type="primary" onClick={()=>{
            onComment()}}>发表评论</Button>
          <Button style={{ marginLeft: 10 }} onClick={() => setShowBtn(false)}>
            取消
          </Button>
        </div>
        </>):(
          <div className="nologin">你尚未登陆，请先登陆账号才可以评论</div>
        )}

          {/* //公共评论部分 */}
      <div className="comment">
      <div className="title">全部评论</div>
      {(listdetailedData[0]?.comments as OtherAuthors[])?.map((item,index) => {
        return (
      <div className="comment-item">
        <Avatar
          className="avatar"
          size="large"
          src={item.createTime.avatarUrl}
        />
        <div className="comment-content">
          <div className="commenter-msg">
            <div className="nickName">
              {item.createTime.name}  第{item.id}楼
              {item.commentId!==null?(<span>  回复  第{item.commentId}楼</span>):""}
              </div>
            
            <div className="content">
            <div dangerouslySetInnerHTML={{ __html: item.content || '' }} />
            </div>
          </div>
          <div className="act-row">
            <span className="act-item">
              <span>X</span>
              <span className="act-text" onClick={()=>{deleteComment(item.id)}}>删除</span>
            </span>
            <span className="act-item">
              <CommentIcon width="15" height="15" />
              <span className="act-text" onClick={() => {
                  if(!root.isLogin){
                    message.error('请先登陆')
                    return 
                  }
                setshowName(`${item.createTime.name}:${item.content}`)
                setZcommentId(item.id)
                setcommentModal(true)
              }
              }>评论</span>
            </span>
          </div>
        </div>
      </div> 
      )
      })}
  </div>
      </Card>
      </div>):(
        <Spin />
      )}
    </div>
    {/* 评论详情Model */}
    <Modal
        title={`回复${showname}的评论`}
        visible={commentModal}
        footer={false}
        onCancel={() => {
          setcommentModal(false)
        }}
      >
        
        <CommentDeatil zcomid={zcommentId} momentId={id} 
        onChangeModel={(value) => {
          setcommentModal(value)
        }} 
        onFetch={()=>fetchdetailed()}
        />
      </Modal>
    </>
  )
}

export default PostPage